import { history } from '@umijs/max';
import axios from 'axios'
const  baseURL =''
const api  = axios.create({
  baseURL: 'http://localhost:44306',
   timeout: 100*1000,
})

export async function sseExport(requestURI:string){
    let newHeard = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
    const token_type = localStorage.getItem('token_type') || '';
    const access_token = localStorage.getItem('access_token') || '';
    const token = `${token_type} ${access_token}`;
    const res = await fetch(newHeard+requestURI,{
      method:'GET',
      headers:{
        Authorization:token
      }
     });
     if(!res){
      return;
     }
     if(!res.ok){
      return;
     }
     if(!res.body){
      return
     }
     const reader = res.body.getReader()
      const decoder = new TextDecoder('utf-8')
      while (true) {
       const { done, value } = await reader.read()
       if (done) {
        break
       }
       const chunk = decoder.decode(value, { stream: true })
       console.log(chunk)
       if (chunk.startsWith('done:')) {
        const fileName = chunk.split(':')[1]
       // downloadExportfile(fileName)
       }
      
      }
  }
  



// Add a request interceptor
api.interceptors.request.use(function (config) {
    // Do something before request is sent
    const token_type = localStorage.getItem('token_type') || '';
    const access_token = localStorage.getItem('access_token') || '';
    if(access_token && config.headers){
        config.headers['Authorization'] = `${token_type} ${access_token}`;
    }
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
api.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log('response',response)
    if(response.status==200){
      
    }
    const {data} = response;
    return data;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
     console.log('error',error.status)
    if(error.status==401){
      history.push('/')
      return
    }
    return Promise.reject(error);
  });
export  default api
